/*******************************************************************************
 * Copyright (c) 2010, 2030 www.itlaobing.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package cn.itlaobing.shopping.dao;

import java.sql.*;


/** 
 * ClassName: DBHelper <br/> 
 * Function: TODO 功能描述 <br/> 
 * date: 2017年9月24日 下午7:49:15 <br/> 
 * 
 * @author 王建蕊 
 * @version 1.0 
 * @since JDK 1.8 
 */
public class DBHelper {
	private Connection conn;
	private PreparedStatement ps;
	private ResultSet rs;
	public static String DRIVER = "com.mysql.jdbc.Driver";
	public static String URL="jdbc:mysql://localhost:3306/orders";
	public static String USER = "root";
	public static String PWD = "root";
	
	static {
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	//打开连接
	private void openConnection() throws ClassNotFoundException, SQLException {
		if (conn == null || conn.isClosed()) {
			conn = DriverManager.getConnection(URL, USER, PWD);
		}
	}

	// 关闭
	public void close() throws  SQLException {
		if (rs != null)
			rs.close();
		if (conn != null)
			conn.close();
		if (ps != null)
			ps.close();
	}

	//参数
	private void setParameter(Object... params) throws ClassNotFoundException, SQLException {
		if (params != null && params.length > 0) {
			for (int i = 0; i < params.length; i++) {
				ps.setObject(i + 1, params[i]);
			}
		}
	}

	// 增删改
	public int executeUpdate(String sql, Object... params) throws ClassNotFoundException, SQLException {
		openConnection();
		ps = conn.prepareStatement(sql);
		setParameter(params);
		return ps.executeUpdate();
	}

	// 查
	public ResultSet executeQuery(String sql, Object... params) throws ClassNotFoundException, SQLException {
		openConnection();
		ps = conn.prepareStatement(sql);
		setParameter(params);
		return ps.executeQuery();
	}
	

}
